package vn.lumi.smarthome.ui.scene;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.io.model.Scene.OnControlSceneListener;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.base.BaseFragmentMain;
import vn.lumi.smarthome.ui.base.DialogLumi;
import vn.lumi.smarthome.ui.base.MainFragment;
import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class SceneFragment extends BaseFragmentMain implements
		LoaderCallbacks<Cursor>, OnControlSceneListener {

	private static final String TAG = "SceneFragment";

	private ListView mListScenes;
	private SceneAdapter mSceneAdapter;
	private TextView tvMsg;

	/**
	 * Bien nay tra ve true thi cho phep bat canh
	 */
	private boolean isAllowedTurnOnScene = true;

	ProgressDialog progressDialog;
	SceneReceiver mReceiver;
	// private static SceneFragment mSceneFragment;
	// Khai bao ID cua Loader
	private static final int LOADER_ID = 1;

	public SceneFragment() {
		LogUltis.i(TAG, "create SceneFragment");
	}

	public static SceneFragment newInstance(int floor_id, int room_id,
			String nameRoom, String nameFloor) {
		// if (mSceneFragment == null) {
		// mSceneFragment = new SceneFragment();
		SceneFragment mSceneFragment = new SceneFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		bundle.putString(MainFragment.NAME_ROOM, nameRoom);
		bundle.putString(MainFragment.NAME_FLOOR, nameFloor);
		mSceneFragment.setArguments(bundle);

		return mSceneFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
		nameRoom = getArguments().getString(MainFragment.NAME_ROOM);
		nameFloor = getArguments().getString(MainFragment.NAME_FLOOR);
		isAllowedTurnOnScene = true;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_scene, container, false);
		init_view(view);

		return view;
	}

	private void init_view(View view) {
		mListScenes = (ListView) view
				.findViewById(R.id.fragment_scene_list_scene);
		tvMsg = (TextView) view.findViewById(R.id.item_list_scene_non_txt);

		mSceneAdapter = new SceneAdapter(getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mSceneAdapter.initData(mFloor_id, mRoom_id);
		mSceneAdapter.setControlScene(this);
		mListScenes.setAdapter(mSceneAdapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		// load data
		refreshData(mFloor_id, mRoom_id, nameRoom, nameFloor);
		// kiem tra xem co cho rung khong
		Config.isVibrate = Preference.getVibrate(getActivity());
		Config.configLanguage(getActivity().getBaseContext(),
				Preference.getLanguage(getActivity().getApplicationContext()));// Thiet
																				// lap
		// ngon ngu
		tvMsg.setText(getString(R.string.txt_msg_dont_scene_on_room));
	}

	@Override
	public void refreshData(int floor_id, int room_id, String nameRoom,
			String nameFloor) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		this.nameRoom = nameRoom;
		this.nameFloor = nameFloor;
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, mFloor_id);
		bundle.putInt(ROOM_ID, mRoom_id);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
		mSceneAdapter.refreshData(floor_id, room_id);
		mSceneAdapter.swapCursor(null);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		int room_id = bundle.getInt(ROOM_ID);
		String selection = TBL_Scene.ROOM_ID + "=?";
		String[] selectionArgs = new String[] { room_id + "" };
		return new CursorLoader(getActivity(), TBL_Scene.CONTENT_URI_SCENE,
				null, selection, selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		mSceneAdapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mSceneAdapter.swapCursor(null);
	}

	private class SceneAdapter extends CursorAdapter {
		Context mContext;
		// int floor_id = 0;
		// int room_id = 0;

//		private static final String TAG = "SceneAdapter";

		private OnControlSceneListener mOnControlSceneListener;

		public SceneAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			mContext = context;
		}

		public void initData(int floorID, int roomID) {
			// floor_id = floorID;
			// room_id = roomID;
		}

		public void refreshData(int floorID, int roomID) {
			// floor_id = floorID;
			// room_id = roomID;
		}

		public void setControlScene(
				OnControlSceneListener onControlSceneListener) {
			this.mOnControlSceneListener = onControlSceneListener;
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {
			final TextView txtName = (TextView) view
					.findViewById(R.id.item_listview_scene_active_txt_name);
			TextView txvSchedule = (TextView) view
					.findViewById(R.id.item_listview_scene_activie_txv_schedule);

			// set name
			final String sceneName = cursor.getString(cursor
					.getColumnIndex(TBL_Scene.NAME));
			txtName.setText(sceneName);

			// set state image
			final int state = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.STATE));
			if (state == Scene.SCENE_STATE_OFF) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
			} else if (state == Scene.SCENE_STATE_ON) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);

			}

			// state image onclick
			final int sceneID = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene._ID));
			txtName.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (isAllowedTurnOnScene) {
						isAllowedTurnOnScene = false;
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();

						// turn on scene
						mOnControlSceneListener.OnTurnOnScene(sceneID);
						progressDialog = DialogLumi.showProgressDialogLumi(
								mContext,
								getString(R.string.txt_msg_apply_scene));
					}
				}
			});

			// set schedule
			final int mode = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.MODE));
			final int hour = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.HOUR));
			final int minute = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.MINUTE));
			if (mode == Scene.SCENE_MODE_AUTO) {
				txvSchedule.setCompoundDrawablesWithIntrinsicBounds(0,
						R.drawable.img_schedule_on, 0, 0);
				txvSchedule.setText(AbstractSceneFragment.padding_str(hour)
						+ ":" + AbstractSceneFragment.padding_str(minute));
			} else if (mode == Scene.SCENE_MODE_NORMAL) {
				txvSchedule.setCompoundDrawablesWithIntrinsicBounds(0,
						R.drawable.img_schedule_off, 0, 0);
				txvSchedule.setText("--:--");
			}
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {
			return View.inflate(context, R.layout.item_listview_scene_active,
					null);
		}

		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return false;
		}

	}

	@Override
	public void OnTurnOnScene(int sceneID) {
		// TODO Auto-generated method stub

		// send to content provider
		ContentValues values = new ContentValues();
		values.put(TBL_Scene._ID, sceneID);
		getActivity().getContentResolver().update(
				TBL_Scene.CONTENT_URI_TURNON_SCENE, values, null, null);

		// //set broadcast receiver
		mReceiver = new SceneReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(getActivity().getString(
				R.string.txt_broadcast_turnOn_scene_successful));
		filter.addAction(getActivity().getString(
				R.string.txt_broadcast_turnOn_scene_failed));
		getActivity().registerReceiver(mReceiver, filter);

	}

	@Override
	public void OnTurnOffScene(int sceneID) {
		// TODO Auto-generated method stub
		ContentValues values = new ContentValues();
		values.put(TBL_Scene._ID, sceneID);
		getActivity().getContentResolver().update(
				TBL_Scene.CONTENT_URI_TURNOFF_SCENE, values, null, null);
	}

	public class SceneReceiver extends BroadcastReceiver {

		// private ProgressDialog mDialog;

		public SceneReceiver() {
			// mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// mDialog.cancel();
			getActivity().unregisterReceiver(mReceiver);

			// Cho phep bat canh tro lai
			isAllowedTurnOnScene = true;
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_turnOn_scene_successful))) {
				DialogLumi.cancelProgressDialogLumi(progressDialog);

			}

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_turnOn_scene_failed))) {
				DialogLumi.cancelProgressDialogLumi(progressDialog);
				DialogLumi.showAlertDialog(context,
						getString(R.string.txt_error),
						getString(R.string.txt_error_cannot_connect_HC));
			}
		}
	}
}
